<template>
  <div class="index-conntainer">
     <div class="content">
       
       <div class="headbtn_box">
           <div class="addbutton"> 
              <el-button type="primary"  size="small" @click="handlerSubmit"  > 保存</el-button> 
               <el-button type="danger"  size="small" @click="handlerBack" > 返回</el-button> 
           </div>
       </div>
       
        <div class="container">
                
            
          <el-form ref="formRef" :model="form"     label-width="100px" label-position="left" size="small"> 
           <div class="mt15" >  
             <el-card class="box-card" shadow="never"> 
             
                 <div class="box_tit"  style="width: 150px; margin-bottom: 18px;">商品基础信息</div>
                
                  <!-- 编辑信息层 -->
                 <div class="edits"  >
                   <el-row  :gutter="15">
                     <el-col :span="8">
                       <el-form-item label="商家名称:" >
                           {{ form.merchantName?  form.merchantName : store.getters['user/username'] }}
                       </el-form-item>
                       
                     </el-col>
                     
                     <el-col :span="8">
                        <el-form-item :label="t('product.categoryId')" prop="categoryId" >
                         <el-select v-model="form.categoryId"  :placeholder="t('common.choose')" size="small">
                             <el-option
                               v-for="item in categoryList"
                               :key="item.id"
                               :label="item.name"
                               :value="item.id"
                             />
                           </el-select>
                       </el-form-item>                     
                     </el-col>
                     
                     <el-col :span="8">
                      <el-form-item label="商品名称" prop="name" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                        <el-input v-model="form.name" placeholder="商品名称" />
                      </el-form-item>
                     </el-col>
                     
                     <el-col :span="8">
                      <el-form-item label="商品价格" prop="price" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                        <el-input v-model="form.price" placeholder="商品价格" />
                      </el-form-item>
                     </el-col>
                     
                     <el-col :span="8">
                      <el-form-item label="状态" prop="isgrounding" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                        <el-radio-group v-model="form.isgrounding">
                           <el-radio
                              v-for="item in shop_background"
                              :key="item.value"
                              :label="item.value"
                           >{{ item.label }}</el-radio>
                        </el-radio-group>
                      </el-form-item>
                     </el-col>  
                     <el-col :span="24">
                       <el-form-item label="商品图片" prop="picture" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                         <el-upload
                             class="avatar-uploader"
                             :action="imageUploadUrl"
                              :headers="header"
                             :show-file-list="false"
                             :on-success="handleAvatarSuccess"
                             :before-upload="beforeAvatarUpload"
                           >
                             <img v-if="form.picture" :src="form.picture" class="avatar" width="350" />
                             <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                           </el-upload>
                       
                         <div style="display:none;">
                           <el-input v-model="form.picture" />
                         </div>
                       </el-form-item>
                     </el-col>
                     
                   </el-row> 
                 </div> 
             </el-card>              
           </div> 
           
           
           <!-- 口味列表配置 -->
           <div class="mt15" >
             <el-card class="box-card" shadow="never">              
                 <div class="box_tit"  style="width: 150px; margin-bottom: 18px;">商品口味</div>
                
                  <el-form-item label="口味配置">
                    <div v-if="form.dishFlavors" class="flavorBox">
                      <!-- 商品本身没有口味数据 -->
                      <el-button v-if="form.dishFlavors.length == 0" type="warning" class="addBut" @click="addFlavor()">+添加口味</el-button>
                  
                      <!--商品本身有口味-->
                      <div v-if="form.dishFlavors.length != 0" class="flavor">
                  
                        <div v-for="(item ,index ) in form.dishFlavors" class="cont">
                          <span>口味名（8个字内）</span>
                           <span class="delFlavor delBut non" @click="delFlavor(index)">删除</span>
                          <!--口味名称 -->   
                          <div style="width: 30%;">
                             <el-form-item   :key="index" :prop="'dishFlavors.' + index + '.name'"  :rules="[{required: true,message: '该值不能为空',trigger: 'blur'}]">
                                  <el-input v-model="item.name" placeholder="请输入口味名称"  maxlength="8" show-word-limit/>
                            </el-form-item>
                           
                          </div>
                          
                  
                        
                          <!-- 口味明细 -->                  
                          <div class="labItems">    
                            <el-tag effect="plain"  type="success" class="labTag" v-for="(tag,ind) in item.value" :key="ind" closable :disable-transitions="false" @close="handleChildrenClose(item,ind)">
                                <ItemEdit    :item="tag"></ItemEdit>
                             </el-tag>   
                            <el-button   class="button-new-tag" size="small" @click="addChildren(item)">+ 添加</el-button>
                          </div>  
                        </div>
                  
                        <el-button type="warning" @click="addFlavor()">添加口味</el-button>
                  
                      </div>
                    </div>                  
                  </el-form-item>
                                 
             </el-card>              
           </div> 
           
           <!-- 商品详情 --> 
           <div class="mt15" >
             <el-card class="box-card" shadow="never">              
                 <div class="box_tit"  style="width: 150px; margin-bottom: 18px;">商品详情</div>
                 
                 <QuillEditor v-model="form.description"  style="min-height: 400px;"/>
             </el-card>              
           </div> 
           
           </el-form> 
        </div> 
      </div> 
      
      <div class="headbtn_box">
          <div class="addbutton"> 
              <el-button type="primary"  size="small" @click="handlerSubmit"  > 保存</el-button> 
              <el-button type="danger"  size="small" @click="handlerBack"  > 返回</el-button> 
          </div>
      </div>
      
      
  </div>
  
</template>

<script setup>
  import { ref, watch} from 'vue'
  import {  Plus } from '@element-plus/icons-vue'
  import { ElMessage  } from 'element-plus'
  import { useRouter } from 'vue-router';
  import store from '@/store/index.js'
  //定义国际化的语言的文件
  import { useI18n } from 'vue-i18n';
  const { t } = useI18n();
  const { proxy } = getCurrentInstance();
  const router = useRouter();
  import {dataApi as categoryDataApi} from '@/api/categoryclass.js'
  import {addApi,updateApi, findByIdApi} from '@/api/product.js'
  
  //图片上传地址
  const imageUploadUrl =ref(process.env.VUE_APP_BASE_API+'/api/upload/image')
  
  const {shop_background} = proxy.useDict('shop_background');
  
   import QuillEditor from '@/components/Editor/index.vue'
   //自定义组件
   import ItemEdit from '@/components/DivItem/edit.vue'
   
 
 //自己的定义额外参数
 const data = reactive({
   header: {
     'Authorization': store.getters['user/accessToken']
   },
   categoryList: [],
   form: {
    picture: undefined,
    isgrounding: '0',
    num: -1,
    // 口味列表
    dishFlavors: [],
    description: undefined
   }
 });
 
 ///自己的定义额外参数,用来使用的
 const { header, categoryList, form} = toRefs(data);
 
  
  function handleAvatarSuccess(res, file) {
    if(res.code===200){
       form.value.picture= res.data.image_url
    }else{
       ElMessage.error( res.msg);
    }     
   } 
   
   function beforeAvatarUpload(file) {
         const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png');
         const isLt2M = file.size / 1024 / 1024 < 2;
   
         if (!isJPG) {
            ElMessage.error('上传头像图片只能是 JPG、PNG 格式!');
         }
         if (!isLt2M) {
            ElMessage.error('上传头像图片大小不能超过 2MB!');
         }
         return isJPG && isLt2M;
   }
   
  
  //查询商品分类
  function fetchCategoryList(){
    const params={page:1,size:1000}
    categoryDataApi(params).then(resp=> {
      categoryList.value= resp.data.rows
    })
  }
  
  fetchCategoryList();
  
  
  //返回，关闭当前路由，返回上级路由
  function handlerBack(){   
    store.dispatch('tabsBar/delRoute', router.currentRoute._value)
    router.go(-1) 
  }
  
  //添加口味
  function addFlavor(){
    //判断item.value[]所有的项目中的name是否都不为空，如果为空提示，停止操作
    const result=form.value.dishFlavors.some(p=> p.name.length===0 );
    if(result){
      ElMessage.error('口味名称有空的值，请补全后再做此项操作!');
      return;
    }
    
    const data= {
      name: '',
      value: []
    }
    form.value.dishFlavors.push(data);
  }
  
  //删除某一个口味对象
  function delFlavor(index){
     form.value.dishFlavors.splice(index,1);
  }
  
  //添加口味明细项
  function addChildren(item){
    //判断item.value[]所有的项目中的name是否都不为空，如果为空提示，停止操作
    const result=item.value.some(p=> p.value.length===0 );
    //有空值
    if(result){
       ElMessage.error('请输入值再后进行此项操作!');
       return;
    }
    
    const data= {
      value: '',
      price: 0
    }
    item.value.push(data);
  }
  
  /**移出属性名称
   * @param {Object} item
   * @param {Object} index
   */
  function handleChildrenClose(item,index){
    item.value.splice(index,1);
  }
  
  
  /**
   * 提交保存
   */
  function handlerSubmit(){    
    //表单验证 
    proxy.$refs["formRef"].validate(valid => {
      if(valid){
        executeUpdate();
      }
    });    
  }
  
  function executeUpdate(){  
      addApi(form.value).then(resp=> {
         ElMessage({message: '新增数据成功.',type: 'success'})
         
         //handlerBack
          ElMessageBox.confirm('新增数据成功，还需要继续添加数据吗?','提示',
             {
               confirmButtonText: '继续添加',
               cancelButtonText: '取消',
               type: 'success',
             }
           )
             .then(() => {
               //继续添加 什么都不要处理，保留用户的数据  
               
             })
             .catch(() => {
               //不要继续添加
               handlerBack();
           })         
      })
  }
  
  // 初始化数据
  function initData(){     
     const params=proxy.$router.currentRoute._value.params;
     if(params.id){
       findByIdApi(params.id).then(resp=> {
         form.value= resp.data
         form.value.id=undefined
         form.value.picture=undefined
         form.value.name=undefined
       }).catch(e=> {
           handlerBack();
       });
     }else{
       //如果没有参数直接关闭
        ElMessage.error('参数错误!');
        handlerBack();
     }
  }
  
  initData();
  
</script>


<style  lang="scss">
  
  .headbtn_box {
      position: relative;
      background-color: white;
      height: 64px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      padding: 0 16px;
      z-index: 1;
      min-width: 950px;
      box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.05);
  
      .addbutton {
          right: 10px;  
          button {
              margin: 0 8px;
          }
      }
  }
  
  .container{
     height: calc(100% - 64px);
     
     .box_tit {
         font-size: 16px;
         font-weight: bold;
         color: #000000;
     
         .el-form-item__label {
             font-size: 16px !important;
             color: #000000 !important;
         }
     }
     
     .mt15{
       margin-top: 15px;
     }
     
     .el-form-item__label, el-form-item__content {
         font-size: 14px;        
     }
     
  }
  .el-tag + .el-tag {
        margin-left: 10px;
      }
      .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
      }
      .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
      }
  
   .flavorBox{
     width:100%;
   }
   .flavorBox .flavor {
     border: solid 1px #dfe2e8;
     border-radius: 3px;
     padding: 15px;
     background: #fafafb;
     width: 96%;
   }
   .flavorBox .flavor .title {
     color: #606168;
   }
  
   .flavor .el-autocomplete {
      width: 150px;
   }
  
   .flavorBox .flavor .cont .labItems {
     display: block;
     border-radius: 3px;
     border: solid 1px #d8dde3;
     background: #fff;
     padding: 0 5px;
     margin-left: 10px;
     margin-top: 20px;
   }
  
  .flavorBox .flavor .cont .labItems2 {
    border-radius: 3px;
    min-height: 39px;
    margin-left: 10px;
     background: #fff;
     line-height: 26px;
     padding-top: 3px;
  }
  
   .flavorBox .flavor .cont  .delFlavor {
     display: inline-block;
     padding: 0 10px;
     color: #f19c59;
     cursor: pointer;
     float: right;
   }
  
   .flavorBox .flavor .cont {
     margin: 10px 0;
     padding: 10px;
     background-color: #fff;
   }
   .flavorBox .title   .kwbq{
      margin-left: 45px;
   }
  
   .labTag{
     height: auto !important;
     margin-top: 10px;
   }
  
   .labItems .el-tag .el-icon-close{
     top: -50px;
   }
  
   .btn-danger{
     color:#f56c6c;
   }
</style>

<style>
  .labItems .el-tag .el-icon-close{
    top: -50px;
  }
</style>
